// pages/vip/vip.js
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLoggedIn: false,
    userInfo: null,
    vipPlans: [
      {
        id: 1,
        name: '月度会员',
        price: '19.9',
        originalPrice: '29.9',
        duration: '1个月',
        features: ['无限次转写', '优先处理', '高级转写模型']
      },
      {
        id: 2,
        name: '季度会员',
        price: '49.9',
        originalPrice: '89.9',
        duration: '3个月',
        features: ['无限次转写', '优先处理', '高级转写模型', '专属客服']
      },
      {
        id: 3,
        name: '年度会员',
        price: '159.9',
        originalPrice: '359.9',
        duration: '12个月',
        features: ['无限次转写', '优先处理', '高级转写模型', '专属客服', '数据导出']
      }
    ],
    currentVipInfo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.checkLoginStatus();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkLoginStatus();
    if (this.data.isLoggedIn) {
      this.getVipInfo();
    }
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus: function () {
    const isLoggedIn = app.globalData.isLoggedIn;
    const userInfo = app.globalData.userInfo;

    this.setData({
      isLoggedIn: isLoggedIn,
      userInfo: userInfo
    });

    if (!isLoggedIn) {
      wx.showModal({
        title: '提示',
        content: '请先登录',
        confirmText: '去登录',
        cancelText: '返回',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          } else {
            wx.navigateBack();
          }
        }
      });
    }
  },

  /**
   * 获取会员信息
   */
  getVipInfo: function () {
    // 模拟获取会员信息
    // 实际应用中，应该从服务器获取
    const mockVipInfo = {
      isVip: true,
      level: '月度会员',
      expireDate: '2023-12-31',
      remainingDays: 30
    };

    this.setData({
      currentVipInfo: mockVipInfo
    });
  },

  /**
   * 购买会员
   */
  buyVip: function (e) {
    const planId = e.currentTarget.dataset.id;
    const plan = this.data.vipPlans.find(item => item.id === planId);

    if (!plan) return;

    wx.showModal({
      title: '购买会员',
      content: `确定购买${plan.name}，价格${plan.price}元吗？`,
      success: (res) => {
        if (res.confirm) {
          // 模拟支付过程
          wx.showLoading({
            title: '支付中...',
          });

          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '购买成功',
              icon: 'success',
              duration: 2000
            });

            // 更新会员信息
            this.getVipInfo();
          }, 1500);
        }
      }
    });
  },

  /**
   * 续费会员
   */
  renewVip: function () {
    wx.showToast({
      title: '请选择会员方案',
      icon: 'none'
    });
  }
})
